﻿namespace IBTrader.Modules.HistoricalData
{
    using IBTrader.Model;
    using IBTrader.Modules.Tws;
    using System.Threading;

    class HistoricalData
    {
        private readonly HistoricalContract contract;
        internal readonly Error Error;
        internal readonly Contract Contract;
        internal readonly Data Data;
        internal readonly File File;
        internal bool Cancelled { get; private set; }
        internal HistoricalData(IIB ib, HistoricalContract contract)
        {
            this.contract = contract;
            Error = new Error(this);
            Contract = new Contract(this, ib, contract);
            Data = new Data(this, ib, contract);
            File = new File(this, contract);
        }
        internal virtual void Next()
        {
            Contract.Next();
            File.End();
            if (!Cancelled && Contract.NextDate())
            {
                if (File.Start())
                    Data.Request();
                else
                    ThreadPool.QueueUserWorkItem(_ => Next());
            }
        }
        internal virtual void Cancel()
        {
            Data.Cancel();
            Cancelled = true;
            Next();
        }
    }
}
